package cn.kgc.vue.controller;

import cn.kgc.vue.commons.QueryCondition;
import cn.kgc.vue.commons.ResponseResult;
import cn.kgc.vue.entity.Template;
import cn.kgc.vue.service.TemplateService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;

/**
 * @author 课工场
 * @date 2023/12/15
 * @description
 */
@Api(tags = "资源中心")
@RestController
@RequestMapping("templates")
public class TemplateController {

    @Resource
    private TemplateService templateService;

    @ApiOperation("资源列表")
    @PostMapping("list")
    public ResponseResult templateList(@RequestBody QueryCondition<Template> queryCondition) {

        return templateService.getTemplateList(queryCondition);
    }

    @ApiOperation("上传模板")
    @PostMapping("upload")
    public ResponseResult uploadTemplate(MultipartFile file) {

        return templateService.uploadTemplate(file);
    }

    @ApiOperation("添加模板信息")
    @PostMapping("add")
    public ResponseResult addTemplateInfo(@RequestBody Template template) {
        templateService.save(template);
        return ResponseResult.success().message("添加成功");
    }


    @ApiOperation("删除模板")
    @DeleteMapping("{uuid}")
    public ResponseResult removeTemplateInfo(@PathVariable String uuid) {

        LambdaQueryWrapper<Template> lambda = new QueryWrapper<Template>().lambda();
        lambda.eq(Template::getUuidName, uuid);
        templateService.remove(lambda);

        File file = new File("D:/upload/" + uuid);
        if (file.exists()) {
            file.delete();
        }

        return ResponseResult.success().message("删除成功");
    }


    @ApiOperation("下载模板")
    @GetMapping("download")
    public void downloadTemplate(String uuid, HttpServletResponse response) {

        File file = new File("D:/upload/" + uuid);
        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            ServletOutputStream outputStream = response.getOutputStream();

            IOUtils.copy(fileInputStream, outputStream);
            outputStream.close();
            fileInputStream.close();

        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
}


